package com.gprinter.ui;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.gprinter.AppApplication;
import com.gprinter.bean.User;
import com.gprinter.connect.DeviceConnFactoryManager;
import com.gprinter.constant.AppConstant;
import com.gprinter.sample.Util;
import com.gprinter.thread.ThreadPool;
import com.gprinter.utils.Constant;
import com.gprinter.utils.DensityUtil;
import com.gprinter.utils.Utils;
import com.sample.R;
import com.tools.command.LabelCommand;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Vector;

import static android.graphics.Bitmap.createBitmap;
import static android.hardware.usb.UsbManager.ACTION_USB_DEVICE_ATTACHED;
import static android.hardware.usb.UsbManager.ACTION_USB_DEVICE_DETACHED;
import static com.gprinter.connect.DeviceConnFactoryManager.ACTION_QUERY_PRINTER_STATE;
import static com.gprinter.constant.AppConstant.ACTION_USB_PERMISSION;

/**
 * 扫码结果页
 * by gprinter
 */
public class ScanActivity extends Activity implements View.OnClickListener {

    private static final String TAG = "ScanActivity";

    private Context context = ScanActivity.this;
    public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];

    public static final String TAG_RESULT = "result";
    public static final int REQUEST_CODE = 110;
    public static final int RESULT_CODE = 119;
    public static final String CONNECT_STATUS = "connect.status";
    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 10000;//请求码，自己定义
    private static final String DEBUG_TAG = "MainActivitysss";
    private static final int MAIN_QUERY_PRINTER_STATUS = 0xfe;
    private static final int REQUEST_PRINT_LABEL = 0xfd;
    private static final int REQUEST_PRINT_RECEIPT = 0xfc;
    private static final int ERROR_MESSAGE_CODE = 200; //Toast错误提示

    public static final int CONN_STATE_DISCONNECT = 0x90;
    public static final int CONN_STATE_CONNECTING = CONN_STATE_DISCONNECT << 1;
    public static final int CONN_STATE_FAILED = CONN_STATE_DISCONNECT << 2;
    public static final int CONN_STATE_CONNECTED = CONN_STATE_DISCONNECT << 3;

    int indextt;
    ImageView lianjie;
    String zhuangtai = "正常";
    private long firstTime = 0;
    private int id = 0;
    private Button scan;
    private WebView web;
    private SharedPreferences sp;
    private String host, duijima, djm_host, service_host;
    private String hosts = "http://www.zhikesys.top";
    private User user;
    private boolean isHost;
    private ProgressBar loading;
    private Spinner spinner;
    private ArrayList<String> data_list;
    private ArrayAdapter<String> arr_adapter;
    private ArrayList<String> data_listId;
    private ThreadPool threadPool;


    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ERROR_MESSAGE_CODE:
                    Utils.toast(ScanActivity.this, (String) msg.obj);
                    break;
                default:
                    break;
            }
        }
    };


    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(DEBUG_TAG, "onCreate");
        sp = getSharedPreferences(LoginActivity.SP_NAME, Context.MODE_PRIVATE);
        setContentView(R.layout.activity_scan);

        initView();
        setData();
        initEvent();

    }

    /**
     * 初始化View设置，ID等
     */
    public void initView() {
        user = (User) getIntent().getExtras().getSerializable(LoginActivity.TAG_USER);
        scan = (Button) findViewById(R.id.scan);
        lianjie = (ImageView) findViewById(R.id.lianjie);
        web = (WebView) findViewById(R.id.webview);
        web.getSettings().setJavaScriptEnabled(true);
        web.addJavascriptInterface(new JavaScriptinterface(this),
                "test");
        loading = (ProgressBar) findViewById(R.id.scan_loading);
        spinner = (Spinner) findViewById(R.id.spinner);
    }

    /**
     * 初始化广播及按钮点击监听
     */
    private void initEvent() {

        //功能按钮点击事件
        scan.setOnClickListener(this);
        lianjie.setOnClickListener(this);

        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(ACTION_USB_DEVICE_DETACHED);
        filter.addAction(ACTION_QUERY_PRINTER_STATE);
        filter.addAction(DeviceConnFactoryManager.ACTION_CONN_STATE);
        filter.addAction(ACTION_USB_DEVICE_ATTACHED);
        registerReceiver(printerReceiver, filter);
    }


    @Override

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.scan:
                requestPermission();
//                printTest();
                break;

            case R.id.lianjie:
                startActivityForResult(new Intent(this,
                        BluetoothDeviceList.class), AppConstant.BLUETOOTH_REQUEST_CODE);
                break;
            default:
                break;
        }

    }


    /**
     * 测试打印效果
     */
    private void printTest() {

        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] == null) {
            Utils.toast(this, "打印机未连接，请检查连接打印机");
            return;
        }

        threadPool = ThreadPool.getInstantiation();
        threadPool.addTask(new Runnable() {
            @Override
            public void run() {
                //
//                sendBeCareLabel("珠海佳博集团", "123456789", "顺丰快递", "电子产品",
//                        "广东省珠海市", "广东省珠海市",
//                        "珠海佳博集团", "4", "2", "1");

//                sendWuLiuLabel("珠海佳博集团", "珠海佳博集团", "123456789",
//                        "电子产品", "顺丰快递", "00", "4", "1", "广东省珠海市", "2");


                sendQrLabel("广东省珠海市", "珠海佳博集团", "珠海佳博集团",
                        "123456", "X-303-8001-8001", "8", "1", "2");

            }
        });
    }


    /**
     * 组件赋值
     */
    private void setData() {
        //数据
        data_list = new ArrayList<String>();
        data_listId = new ArrayList<String>();
        for (int i = 0; i < user.getWordname().size(); i++) {
            data_list.add(user.getWordname().get(i).getName());
            data_listId.add(user.getWordname().get(i).getId());

        }


        //适配器
        arr_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner.setAdapter(arr_adapter);
        spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {//选择item的选择点击监听事件
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                indextt = arg2;
                // TODO Auto-generated method stub
                // 将所选mySpinner 的值带入myTextView 中
                Toast.makeText(ScanActivity.this, "您已切换到岗位：" + data_list.get(arg2), Toast.LENGTH_LONG).show();//文本说明
                LoadWebView(user.getWordname().get(arg2).getName(), user.getWordname().get(arg2).getId());
            }

            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });


        if (sp.getString(LoginActivity.SERVICE_HOST, null) != null) {
            service_host = sp.getString(LoginActivity.SERVICE_HOST, "");
        }
        if (sp.getBoolean(LoginActivity.IS_SERVICE_HOST, false)) {
            isHost = sp.getBoolean(LoginActivity.IS_SERVICE_HOST, false);
        }
        if (sp.getString(LoginActivity.DUIJIEMA, null) != null) {
            duijima = sp.getString(LoginActivity.DUIJIEMA, null);
        }
        if (sp.getString(LoginActivity.DJM_HOST, null) != null) {
            djm_host = sp.getString(LoginActivity.DJM_HOST, null);
        }
        host = isHost ? service_host : djm_host;
        //"http://139.199.132.212:8030";
        scan.setOnClickListener(this);
        if (data_list.size() > 0) {
            LoadWebView(data_list.get(0), data_listId.get(0));
        }
    }


    void LoadWebView(String wordname, String wordId) {
        try {
            web.loadUrl(hosts + "/ExecuteSqlSaotiaomaapp.aspx?"
                    + "duijiema=" + URLEncoder.encode(duijima, LoginActivity.TAG_C0DE)
                    + "&user=" + URLEncoder.encode(user.getUsername(), LoginActivity.TAG_C0DE)
                    + "&tiaomabiaoshi=" + URLEncoder.encode(wordId, LoginActivity.TAG_C0DE)
                    + "&wordname=" + URLEncoder.encode(wordname, LoginActivity.TAG_C0DE));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.e("gprinter", "start weburl-------->" + web.getUrl());
        web.getSettings().setJavaScriptEnabled(true);
        web.setWebViewClient(new WebViewClient());
        web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                if (newProgress == 100) {
                    // 网页加载完成
                    loading.setVisibility(View.GONE);
                } else {
                    // 加载中

                }

            }
        });
    }

    @Override
    public void onDestroy() {
        Log.e(DEBUG_TAG, "onDestroy");
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(ScanActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = secondTime;
                return true;
            } else {
                System.exit(0);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //判断请求码
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_CAMERA) {
            //grantResults授权结果
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //成功，开启摄像头
                requetScan();
            } else {
                //授权失败
                Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }

    //TODO 这里webView
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQUEST_CODE:
                if (resultCode == RESULT_CODE) {
                    loading.setVisibility(View.VISIBLE);
                    try {
                        web.loadUrl(hosts + "/ExecuteSqlSaotiaomaapp.aspx?" +
                                "mbtypeid=01" +
                                "&type=appExcuteStatus" +
                                "&tiaomabiaoshi=" + URLEncoder.encode(
                                user.getWordname().get(indextt).getId(), LoginActivity.TAG_C0DE) +
                                "&ordernumber=" + URLEncoder.encode(
                                data.getStringExtra(TAG_RESULT), LoginActivity.TAG_C0DE) +
                                "&duijiema=" + URLEncoder.encode(
                                duijima, LoginActivity.TAG_C0DE) +
                                "&user=" + URLEncoder.encode(
                                user.getUsername(), LoginActivity.TAG_C0DE) +
                                "&wordname=" + URLEncoder.encode(
                                user.getWordname().get(indextt).getName(), LoginActivity.TAG_C0DE)
                                + "&islanyastatus=" + zhuangtai
                        );
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    Log.e("gprinter", "now weburl-------->" + web.getUrl());
                }
                break;
            case AppConstant.BLUETOOTH_REQUEST_CODE: {  //蓝牙连接

                if (data == null) {
                    return;
                }
                closePort();
                    /*获取蓝牙mac地址*/
                String macAddress = data.getStringExtra(BluetoothDeviceList.EXTRA_DEVICE_ADDRESS);
                Log.e(TAG, "macAddress: " + macAddress);
                //初始化话DeviceConnFactoryManager
                new DeviceConnFactoryManager.Build()
                        .setId(id)
                        //设置连接方式
                        .setConnMethod(DeviceConnFactoryManager.CONN_METHOD.BLUETOOTH)
                        //设置连接的蓝牙mac地址
                        .setMacAddress(macAddress)
                        .build();
                //打开端口
                threadPool = ThreadPool.getInstantiation();
                threadPool.addTask(new Runnable() {
                    @Override
                    public void run() {
                        DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].openPort();
                    }
                });

                break;
            }
            default:
                break;
        }
    }

    BroadcastReceiver printerReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {

                //Usb连接断开、蓝牙连接断开广播
                case ACTION_USB_DEVICE_DETACHED:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] != null) {
                                DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].closePort(id);
                                Utils.toast(ScanActivity.this, "连接已断开");
                            }
                        }
                    });
                    break;
                case DeviceConnFactoryManager.ACTION_CONN_STATE:
                    int state = intent.getIntExtra(DeviceConnFactoryManager.STATE, -1);
                    int deviceId = intent.getIntExtra(DeviceConnFactoryManager.DEVICE_ID, -1);
                    switch (state) {
                        case DeviceConnFactoryManager.CONN_STATE_DISCONNECT:
                            if (id == deviceId) {
                                Utils.toast(context, "连接已断开，请重新连接打印机");
                                lianjie.setImageResource(R.drawable.no);
                            }
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTING:
                            Utils.toast(context, "正在连接打印机");
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTED:
                            Utils.toast(context, "打印机连接成功");
                            lianjie.setImageResource(R.drawable.ok);
                            break;
                        case CONN_STATE_FAILED:
                            Utils.toast(context, "打印机连接失败，请检查");
                            lianjie.setImageResource(R.drawable.no);
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
        }
    };


    /**
     * 调用扫码页面
     */
    private void requetScan() {
        Intent intent = new Intent(ScanActivity.this, CommonScanActivity.class);
        intent.putExtra(Constant.REQUEST_SCAN_MODE, Constant.REQUEST_SCAN_MODE_QRCODE_MODE);
        startActivityForResult(intent, REQUEST_CODE);
    }


    /**
     * 请求权限
     */
    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            /**
             * 第一次请求权限时，用户如果拒绝，下一次请求调用shouldShowRequestPermissionRationale()
             * 方法返回true
             * 向用户解释为什么需要这个权限
             */
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                new AlertDialog.Builder(this)
                        .setMessage("申请相机权限")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //申请相机权限
                                ActivityCompat.requestPermissions(ScanActivity.this,
                                        new String[]{Manifest.permission.CAMERA,
                                                Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                            }
                        }).show();
            } else {
                //申请相机权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_CALL_CAMERA);
            }
        } else {
            requetScan();
        }
    }


    /**
     * 重新连接回收上次连接的对象，避免内存泄漏
     */
    private void closePort() {
        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] != null
                && DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].mPort != null) {
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].reader.cancel();
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].mPort.closePort();
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].mPort = null;
        }
    }


    /**
     * 打印带二维码面单
     *
     * @param address 地址
     * @param weizhui 底部公司名称
     * @param account 客户
     * @param order   订单号
     * @param mode    型号
     * @param total   一共N块
     * @param di      第N包
     * @param number  一共N包
     */
    void sendQrLabel(String address, String weizhui, String account, String order
            , String mode, String total, String di, String number) {


        // 发送数据
        try {
            InputStream is = getResources().getAssets().open("Qr.bin");
            byte[] bytes = new byte[is.available()];
            while ((is.read(bytes)) != -1) {
            }
//            String data = Base64.encodeToString(bytes, Base64.DEFAULT);

            Vector vector = new Vector();
            for (byte b : bytes) {
                vector.add(Byte.valueOf(b));
            }
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].sendDataImmediately(vector);

//            mGpService.sendLabelCommand(mPrinterIndex, data);
            is.close();
        } catch (Exception e) {
            mHandler.obtainMessage(ERROR_MESSAGE_CODE, e.getMessage()).sendToTarget();
            Log.e(TAG, "Error: " + e.toString());
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].closePort(id);
            e.printStackTrace();

            return;
        }
        LabelCommand command = new LabelCommand();
        Bitmap bitmap = null;

        bitmap = getBitmap(address, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(190, 160, bitmap.getWidth(), bitmap);
        }
        bitmap = getBitmap(order, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(480, 160, bitmap.getWidth(), bitmap);
        }

        bitmap = getBitmap(account, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(368, 160, bitmap.getWidth(), bitmap);
        }

        bitmap = getBitmap(mode, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(276, 160, bitmap.getWidth(), bitmap);
        }

        bitmap = getBitmap("共 " + total + " 块，共 " + number +
                " 包第    包", DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(104, 160, bitmap.getWidth(), bitmap);
        }

        String start = "@1 = \"" + di + "\"\n";

        command.addUserCommand(start);

        String str = "TEXT 132,510,\"3\",90,1,1,@1\n";

        command.addUserCommand(str);

        String qr = "QRCODE 368,586,H,8,A,0,\"" + order + "\"\n";

        command.addUserCommand(qr);

        bitmap = getBitmap(weizhui, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(25, 15, bitmap.getWidth(), bitmap);
        }

        command.addPrint((Integer.parseInt(number) - Integer.parseInt(di) + 1), 1);
        Vector<Byte> datas = command.getCommand(); // 发送数据

        try {
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].sendDataImmediately(datas);
        } catch (Exception e) {
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].closePort(id);
            Log.e(TAG, "Error: " + e.toString());
            mHandler.obtainMessage(ERROR_MESSAGE_CODE, e.getMessage()).sendToTarget();
            e.printStackTrace();
        }
    }

    /**
     * 发送打印物流面单指令
     *
     * @param account  客户名称
     * @param weizhui  底部公司名称
     * @param order    订单号
     * @param mode     型号
     * @param wuliu    物流名称
     * @param chanpin
     * @param piece    一共N块
     * @param index    第N包
     * @param address  地址
     * @param packages 一共N包
     */
    void sendWuLiuLabel(String account, String weizhui, String order, String mode, String wuliu
            , String chanpin, String piece, String index, String address, String packages) {
        try {
            InputStream is = getResources().getAssets().open("wuliu.bin");
            byte[] bytes = new byte[is.available()];
            while ((is.read(bytes)) != -1) {
            }
//            String data = Base64.encodeToString(bytes, Base64.DEFAULT);
            Vector vector = new Vector();
            for (byte b : bytes) {
                vector.add(Byte.valueOf(b));
            }
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].sendDataImmediately(vector);

            is.close();
        } catch (Exception e) {
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].closePort(id);
            Log.e(TAG, "Error: " + e.toString());
            mHandler.obtainMessage(ERROR_MESSAGE_CODE, e.getMessage()).sendToTarget();
            e.printStackTrace();
            return;
        }

        LabelCommand command = new LabelCommand();
        Bitmap bitmap = null;

        bitmap = getBitmap(order, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(472, 150, bitmap.getWidth(), bitmap);
        }

        bitmap = getBitmap(wuliu, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(472, 590, bitmap.getWidth(), bitmap);
        }

        bitmap = getBitmap(account, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(375, 150, bitmap.getWidth(), bitmap);
        }

        bitmap = getBitmap(mode, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(276, 150, bitmap.getWidth(), bitmap);
        }

        bitmap = getBitmap(address, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(186, 150, bitmap.getWidth(), bitmap);
        }

        bitmap = getBitmap("共 " + piece + " 块，共 " +
                packages + " 包第    包", DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(100, 150, bitmap.getWidth(), bitmap);
        }

        String start = "@1 = \"" + index + "\"\n";

        command.addUserCommand(start);

        String str = "TEXT 130,510,\"3\",90,1,1,@1\n";

        command.addUserCommand(str);

        bitmap = getBitmap(weizhui, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(25, 15, bitmap.getWidth(), bitmap);
        }
        command.addPrint((Integer.parseInt(packages) - Integer.parseInt(index) + 1), 1);
        Vector<Byte> datas = command.getCommand(); // 发送数据
        try {
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].sendDataImmediately(datas);
        } catch (Exception e) {
            e.printStackTrace();
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].closePort(id);
            Log.e(TAG, "Error: " + e.toString());
            mHandler.obtainMessage(ERROR_MESSAGE_CODE, e.getMessage()).sendToTarget();
            e.printStackTrace();
        }

    }


    /**
     * 发送小心易碎指令
     *
     * @param weizhui             底部公司名称
     * @param order               订单号
     * @param wuliu               建议物流名称
     * @param product             产品类型
     * @param address             地址
     * @param installationAddress 安装地址
     * @param dealer              经销商
     * @param piece               一共N件
     * @param packages            一共N包
     * @param index               第N包
     */
    void sendBeCareLabel(String weizhui, String order, String wuliu, String product,
                         String address, String installationAddress,
                         String dealer, String piece, String packages, String index) {
        try {
            InputStream is = getResources().getAssets().open("xiaoxin.bin");
            byte[] bytes = new byte[is.available()];
            while ((is.read(bytes)) != -1) {
            }
//            String data = Base64.encodeToString(bytes, Base64.DEFAULT);
            Vector vector = new Vector();
            for (byte b : bytes) {
                vector.add(Byte.valueOf(b));
            }
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].sendDataImmediately(vector);
            is.close();
        } catch (Exception e) {
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].closePort(id);
            Log.e(TAG, "Error: " + e.toString());
            mHandler.obtainMessage(ERROR_MESSAGE_CODE, e.getMessage()).sendToTarget();
            e.printStackTrace();
            return;
        }
        LabelCommand command = new LabelCommand();
        Bitmap bitmap = null;

        //订单号
        bitmap = getBitmap(order, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(500, 530, bitmap.getWidth(), bitmap);
        }

        //经销商
        bitmap = getBitmap(dealer, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(420, 360, bitmap.getWidth(), bitmap);
        }

        bitmap = getBitmap(address, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(360, 360, bitmap.getWidth(), bitmap);
        }

        bitmap = getBitmap(installationAddress, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(305, 360, bitmap.getWidth(), bitmap);
        }

        bitmap = getBitmap(product, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(245, 360, bitmap.getWidth(), bitmap);
        }

        bitmap = getBitmap(wuliu, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(180, 360, bitmap.getWidth(), bitmap);
        }

        bitmap = getBitmap("共 " + piece + " 块，共 " +
                packages + " 包第   包", DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(110, 360, bitmap.getWidth(), bitmap);
        }

        String start = "@1 = \"" + index + "\"\n";

        command.addUserCommand(start);

        String str = "TEXT 140,705,\"3\",90,1,1,@1\n";

        command.addUserCommand(str);

        bitmap = getBitmap(weizhui, DensityUtil.convertPixelsToSP(context, 36));
        if (bitmap != null) {
            command.addBitmap(25, 15, bitmap.getWidth(), bitmap);
        }
        command.addPrint((Integer.parseInt(packages) - Integer.parseInt(index) + 1), 1);
        Vector<Byte> datas = command.getCommand(); // 发送数据
        Byte[] Bytes = datas.toArray(new Byte[datas.size()]);
        byte[] bytes = toPrimitive(Bytes);
        try {
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].sendDataImmediately(datas);
        } catch (Exception e) {
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].closePort(id);
            Log.e(TAG, "Error: " + e.toString());
            mHandler.obtainMessage(ERROR_MESSAGE_CODE, e.getMessage()).sendToTarget();
            e.printStackTrace();
        }
    }

    /**
     * 文字转化为图片
     *
     * @param data 文字内容
     * @param size 文字字体大小
     * @return Bitmap
     */
    public Bitmap getBitmap(String data, int size) {
        TextView tv = new TextView(this);
        tv.setTextSize(size);
        tv.setText(data);
//        tv.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
        tv.setTypeface(Typeface.createFromAsset(getAssets(), "SIMYOU.TTF"), Typeface.NORMAL);
        tv.setBackgroundColor(Color.WHITE);
        tv.setDrawingCacheEnabled(true);
        tv.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());
        Bitmap bitmap = createBitmap(tv.getWidth(), tv.getHeight(), Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        tv.draw(canvas);
        Matrix matrix = new Matrix();
        matrix.setRotate(90);
        Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        //千万别忘最后一步
        tv.destroyDrawingCache();
        return result;
    }

    public static byte[] toPrimitive(Byte[] array) {
        if (array == null) {
            return null;
        } else if (array.length == 0) {
            return EMPTY_BYTE_ARRAY;
        } else {
            byte[] result = new byte[array.length];

            for (int i = 0; i < array.length; ++i) {
                result[i] = array[i].byteValue();
            }

            return result;
        }
    }


    /**
     * java与JS交互方法
     */
    public class JavaScriptinterface {
        Context context;

        public JavaScriptinterface(Context c) {
            context = c;
        }

        /**
         * 与js交互时用到的方法，在js里直接调用的
         */
        @JavascriptInterface
        public void hello(String ssss, String ssss2, String ssss3, String ssss4) {
            Log.e("111", "hello");
            Intent intent = new Intent(ScanActivity.this, TJ_Activity.class);
            intent.putExtra("key1", ssss);
            intent.putExtra("key2", ssss2);
            intent.putExtra("key3", ssss3);
            intent.putExtra("key4", ssss4);
            startActivity(intent);
        }

        /**
         * 参数2
         *
         * @param a 打包数量
         * @param b 标签类型
         * @param c 订单编号
         * @param d 客户姓名(经销商)
         * @param e 客户地址
         * @param f 终端地址
         * @param g 产品分类
         * @param h 产品型号
         * @param i 产品颜色
         * @param j 建议物流
         * @param k 产品数量
         * @param l 公司名称
         */


        @JavascriptInterface
        public void dayin(final String a, final String b, final String c, final String d,
                          final String e, final String f, final String g, final String h,
                          String i, final String j, final String k, final String l) {
            Log.e(TAG, "打包数量" + a);
            Log.e(TAG, "标签类型" + b);
            Log.e(TAG, "終端地址" + f);


            if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] == null) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Utils.toast(ScanActivity.this, "打印机未连接，请检查连接打印机");
                    }
                });
                return;
            }

            threadPool.addTask(new Runnable() {
                @Override
                public void run() {
                    if (b.equals("1")) {
                        sendWuLiuLabel(d, l, c, h, j, g, k, "1", f, a);
                    } else if (b.equals("2")) {
                        sendBeCareLabel(l, c, j, g, e, f, d, k, a, "1");
                    } else if (b.equals("3")) {
                        sendQrLabel(f, l, d, c, h, k, "1", a);
                    }
                }
            });
        }


    }

}


